package org.extframework.ld.http.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;

import org.extframework.ld.bean.Power;
import org.extframework.ld.bean.model.IUser;
import org.extframework.ld.conf.PageType;
import org.extframework.ld.conf.ParameterNames;
import org.extframework.ld.content.ExtContent;
import org.extframework.ld.control.ExtXmlControl;
import org.extframework.ld.http.abstr.AbstractEncryptionWebRequest;
import org.extframework.ld.http.abstr.AbstractEncryptionWebResponse;
import org.extframework.ld.http.abstr.AbstractEncryptionWebServlet;
import org.extframework.ld.service.PowerManager;
import org.extframework.ld.service.SysManager;
import org.extframework.ld.util.ExtMessage;
import org.extframework.ld.util.UtilJSON;
import org.extframework.ld.xml.ExtPageXmlControl;
import org.extframework.ld.xml.base.DialogProperties;
import org.extframework.ld.xml.base.ExtParameter;
import org.hibernate.hql.ast.QuerySyntaxException;

import com.alibaba.fastjson.JSON;

/**
 * @fileName : com.sys.action.ExtServlet.java
 * @author : Dong.Li
 * @created : 2012-11-23
 * @version : 1.0
 * @description :
 * ALL RIGHTS RESERVED,COPYRIGHT(C) FCH LIMITED 2012
 */
public class ExtServlet extends AbstractEncryptionWebServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ExtPageXmlControl pageXmlControl;
	private SysManager sysManager;
	private PowerManager powerManager;
	
	public void menu(AbstractEncryptionWebRequest request,AbstractEncryptionWebResponse response) throws IOException{
		String tempMenuId = request.getParameter(ParameterNames.MENU_ACTION_MARK);
		
		Object object = request.getSession().getAttribute(ParameterNames.LOGIN_USER_MARK);
		if(object==null){
			response.printJson("登录超时,请刷新页面,重新登录");
			return;
		}
		IUser users = null;
		if(object !=null && object instanceof IUser){
			users = (IUser) object;
		}
		
		List<Power> powers = powerManager.getPowersByUserId(users.getId());
		
		if(tempMenuId.equalsIgnoreCase(ParameterNames.MENU_ROOT_MARK)){
			response.printJson(ExtXmlControl.getRootMenu(powers));
		}else{
			response.printJson(ExtXmlControl.getMenuNodes(tempMenuId, powers));
		}
	}
	
	
	public void gridHead(AbstractEncryptionWebRequest request,AbstractEncryptionWebResponse response) throws IOException{
		try{
			String treeId = request.getParameter("tree");
			String pageId = ExtContent.getPageId(treeId);
			
			String location = pageXmlControl.getCustomPageLocation(pageId);
			String result = null;
			
			if(location == null){
				String clum = pageXmlControl.getPageHeadToJson(pageId);
				
				String storeFiled =  pageXmlControl.getPageStoreFiled(pageId);
				
				Object obj = request.getSession().getAttribute(ParameterNames.LOGIN_USER_MARK);
				if(obj==null){
					response.printJson(ExtMessage.showErrorMessage("登录超时,请刷新页面,重新登录"));
					return;
				}
				List<Power> powers = powerManager.getPowersByUserId(((IUser)obj).getId(),treeId);
				String menus = pageXmlControl.getRightByUser(powers);
				//由于渲染模式 不能为JAVA 字符串转换后JOSIN带“” 则默认替换成JS运行代码
				clum = clum.replaceAll("\" *script-begin *", "");
				clum = clum.replaceAll(" *script-end *\"", "");
				//clum = clum.replaceAll("function(){return \"\"}", "");
				result  = "{success:true,storeFiled:"+storeFiled+",clum:"+clum+",menus:"+menus+"}";
			}else{
				result  = "{success:true,customData:{location:\""+location+"\"}}";
			}
			response.printEncryptionJson(result);
		}catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			response.printEncryptionJson(ExtMessage.showErrorMessage(e.getMessage()));
		}
	}
	
	
	public void dialog(AbstractEncryptionWebRequest request,AbstractEncryptionWebResponse response) throws IOException{
		try {
			String dialogId = request.getParameter("dialogId");
			String selectId = request.getParameter("selectId");
			
			DialogProperties properties = pageXmlControl.getDialogProperties(dialogId);
			properties.setParentSelectId(selectId);
			String dialogProperties = pageXmlControl.getDialogPropertiesTOJson(properties);
			
			
			String result = "";
			if(properties.getDealogType().equals(PageType.EDIT)){
				
				String hql = pageXmlControl.getDialogHql(dialogId).replaceAll(ParameterNames.SELECT_DATA_MARK, selectId);
				String dialogItems = "";
				if(hql.trim().length()==0){
					dialogItems = pageXmlControl.getDialogItemTOJson(dialogId,null);
				}else{
					Map<String, List<Object[]>> map = sysManager.getObjects(hql, 0, 1);
					dialogItems = pageXmlControl.getDialogItemTOJson(dialogId,map.entrySet().iterator().next().getValue());
				}
				dialogItems = dialogItems.replaceAll("\"store\"", "store");
				dialogItems = dialogItems.replaceAll("\"##", "");
				dialogItems = dialogItems.replaceAll("##\"", "");
				result = "{success:true,dialog:"+dialogItems+",properties:"+dialogProperties+"}";
				
			}else if(properties.getDealogType().equals(PageType.DETAIL)){
				
				String storeFiled =  pageXmlControl.getPageStoreFiled(dialogId);
				Object obj = request.getSession().getAttribute(ParameterNames.LOGIN_USER_MARK);
				if(obj==null){
					response.printJson(ExtMessage.showErrorMessage("登录超时,请刷新页面,重新登录"));
					return;
				}
				String clum = pageXmlControl.getPageHeadToJson(dialogId);
				String rightId = ExtContent.getRightId(dialogId);
				List<Power> powers = powerManager.getPowersByUserId(((IUser)obj).getId(),rightId);
				String menus = pageXmlControl.getRightByUser(powers);
				//由于渲染模式 不能为JAVA 字符串转换后JOSIN带“” 则默认替换成JS运行代码
				clum = clum.replaceAll("\" *script-begin *", "");
				clum = clum.replaceAll(" *script-end *\"", ""); 
				result = "{success:true,storeFiled:"+storeFiled+",clum:"+clum+",menus:"+menus+",properties:"+dialogProperties+"}";
				
			}else if(properties.getDealogType().equals(PageType.CUSTOM)){
				String location = pageXmlControl.getCustomTOJson(dialogId);
				result  = "{success:true,customData:"+location+",properties:"+dialogProperties+"}";
			}
			
			response.printJson(result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			ExtMessage.showErrorMessage(e.getMessage());
		}
	}
	
	
	public void gridData(AbstractEncryptionWebRequest request,AbstractEncryptionWebResponse response) throws IOException{
		
		String menuId = request.getParameter("menuName");
		String tempLimit = request.getParameter("limit");
		String tempStart = request.getParameter("start");
		String paramStr = request.getParameter("param");
		
		String parentSelectIdStr = request.getParameter("parentSelectId");
		Long  parentSelectId = null;
		
		if(!parentSelectIdStr.equals("undefined")){
			try{
				parentSelectId = Long.parseLong(parentSelectIdStr);
			}catch (NumberFormatException e) {
				logger.error(e.getMessage(), e);
				response.printJson("页面传值异常.");
				e.printStackTrace();
				return;
			}
		}
		
		try {
			
			String param = " ";
			int limit = 18,start = 0;
			if(tempLimit!=null){
				limit = Integer.parseInt(tempLimit);
			}
			if(tempStart!=null){
				start = Integer.parseInt(tempStart);
			}
			
			if(paramStr!=null){
				ExtParameter parameter = JSON.parseArray(paramStr, ExtParameter.class).get(0);
				param+=parameter.queryString();
			}
			
			String pageId = ExtContent.getPageId(menuId);
			pageId = pageId==null?menuId:pageId;
			
			
			String hql = pageXmlControl.getPageHql(pageId);
			hql = hql.replaceAll(ParameterNames.PARMETER_MARK, param);
			
			if(hql.indexOf(ParameterNames.HQL_USER_MARK) > -1){
				Object obj = request.getSession().getAttribute(ParameterNames.LOGIN_USER_MARK);
				if(obj==null){
					response.printJson("登录超时,请刷新页面,重新登录");
					return;
				}
				hql = hql.replaceAll(ParameterNames.HQL_USER_MARK, ((IUser)obj).getId().toString());
			}
			
			if(parentSelectId!=null){
				hql = hql.replaceAll(ParameterNames.SELECT_DATA_MARK, parentSelectId.toString());
			}else{
				if(hql.indexOf(ParameterNames.SELECT_DATA_MARK) > -1){
					response.printJson("页面传值异常.");
					return;
				}
			}
			
			Map<String, List<Object[]>> dataMap = sysManager.getObjects(hql, start, limit);
			Entry<String, List<Object[]>> objects = dataMap.entrySet().iterator().next();
			
			String storeFiled = pageXmlControl.getPageStoreFiled(pageId);
			String json = UtilJSON.toJSON(objects.getValue(), storeFiled);
			//System.out.println(json);
			
			StringBuffer buffer = new StringBuffer();
			buffer.append("{countSize:");
			buffer.append(objects.getKey());
			buffer.append(",records:[");
			buffer.append(json);
			buffer.append("]}");
//			System.out.println(buffer.toString());
			response.printJson(buffer.toString());
		} catch (QuerySyntaxException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			if(paramStr!=null){
				response.printJson("查询异常!请检查条件判断是否正确[字符类型不能用大于或等于作为查询条件]");
			}else{
				response.printJson("系统内部异常.");
			}
		}catch (Exception e) {
			logger.error(e.getMessage(), e);
			response.printJson("系统内部异常.");
			e.printStackTrace();
		}
		
	}
	
	protected void init(AbstractEncryptionWebRequest req,
			AbstractEncryptionWebResponse resp) throws ServletException,
			IOException {
		sysManager = getBean(SysManager.class);
		pageXmlControl = getBean(ExtPageXmlControl.class);
		powerManager = getBean(PowerManager.class);
	}


	public void index(AbstractEncryptionWebRequest paramHttpServletRequest,
			AbstractEncryptionWebResponse paramHttpServletResponse)
			throws ServletException, IOException {
		
	}
	

}
